## TV4 Play have an API but it isn't for public use
module Shin
  module Play
    class Tv4play

      def new
        self
      end

      # Programs
      def programs
        # Response
        response = Base.get('http://webapi.tv4play.se/play/programs?per_page=900&page=1')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Data
        data = Oj.load(response.body) rescue nil

        # Can't be nil
        if data != nil
          data['results'].to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end

      end

      # Videos
      def videos(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""

        # Response
        response = Base.get('http://webapi.tv4play.se/play/video_assets?type=episode&is_live=false&platform=web&per_page=99999&node_nids=' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Data
        data = Oj.load(response.body) rescue nil

        # Can't be nil
        if data != nil
          data['results'].to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end

      end

      # Video
      def video(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""

        # Response
        response = Base.get('http://webapi.tv4play.se/play/video_assets?id=' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Data
        data = Oj.load(response.body) rescue nil

        # Can't be nil
        if data != nil
          if data['total_hits'] == 0
            raise NotValid, "No results"
          else
            data['results'].first.to_hashugar
          end

        else
          raise NotValid, "Couldn't parse the JSON"
        end
      end

      # Movies
      def movies
        # Response
        response = Base.get('http://webapi.tv4play.se/play/movie_assets?platform=web&start=0&rows=9999')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Data
        data = Oj.load(response.body) rescue nil

        # Can't be nil
        if data != nil
          data['results'].to_hashugar
        else
          raise NotValid, "Couldn't parse the JSON"
        end

      end

      # Errors
      class NotValid         < StandardError; end
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end
